import React, { useImperativeHandle, useMemo } from "react";
import { Button, Card, Input, InputNumber, message, Popover, Space, Table, Tag } from "antd";
import { useState, useRef, useEffect } from "react";
import { PlusOutlined, FolderOpenOutlined, DeleteOutlined, CloseOutlined, DoubleRightOutlined } from '@ant-design/icons';
import { messageError, messageSuccess } from "@/common/methods";

const EditSkuTable = ({ onRef }) => {
    const [submitList, setSubmitList] = useState([]); // 提交数据
    const [specContent, setSpecContent] = useState([]); //规格内容
    const [specLabelStr, setSpecLabelStr] = useState('');// 规格名称输入值
    const [visible, setVisible] = useState(false); // 点击添加规格按钮控制获取input 元素,控制输入默认选择focus
    const inputRef = useRef(null);// 规格输入框
    const [inputVisible, setInputVisible] = useState(false);
    const [inputTagValue, setInputTagValue] = useState('');
    const [tagIndex, setTagIndex] = useState(null)
    const tagInputRef = useRef(null);


    // 添加规格名称
    function onAddSpecLabel() {
        if (specLabelStr) {
            setSpecContent(specContent.concat({ label: specLabelStr, tags: [] }));
            setSpecLabelStr('');
            // message.success('添加规格明成功');
            messageSuccess("添加规格成功")
            tableSku();
        } else {
            // message.error('请填写规格名称');
            messageError("请填写规格名称")
        }
    }

    // 删除规格
    function onDeleteSpec(index) {
        const specList = [...specContent];
        specList.splice(index, 1);
        setSpecContent(specList);
        messageSuccess('删除规格成功');
        tableSku();
    }

    // 添加规格值
    function onAddSpecTag(index) {
        if (inputTagValue) {
            const specList = [...specContent];
            specList[index].tags.push(inputTagValue);
            setSpecContent(specList);
            setInputTagValue('');// 清空输入内容
            tableSku();
            messageSuccess('添加规格值成功');
        }
        setInputVisible(false);
    }
    //删除规格值 
    function onDeleteSpecTag(labelIndex, tagIndex) {
        const specList = [...specContent];
        specList[labelIndex].tags.splice(tagIndex, 1);
        setSpecContent(specList);
        tableSku();
    }

    function tableSku() {// 绘制商品规格sku
        let temp = [];
        specContent.forEach((item, index) => {
            if (!temp.length) {
                // specContent当只有一个数据时候只需要
                temp.push(...item.tags.map(str => {
                    const oldItem = submitList.find(t => t.sku === str);
                    if (oldItem) {
                        return { ...oldItem };
                    } else {
                        return {
                            [`skuName${index + 1}`]: item.label,
                            [`skuValue${index + 1}`]: str,
                            [item.label]: str,
                            stock: 0,
                            imgUrl: "",
                            piece: 0,
                            linePiece: 0,
                            sku: str
                        }
                    }
                }))
            } else {
                const array = [];
                temp.forEach(obj => {
                    if (item.tags.length === 0) array.push(obj);
                    array.push(
                        ...item.tags.map(t => {
                            obj.sku && (obj.sku = obj.sku + t);
                            const oldItem = submitList.find(t => t.sku === obj.sku);
                            if (oldItem) {
                                return { ...oldItem };
                            } else {
                                return {
                                    ...obj,
                                    [`skuName${index + 1}`]: item.label,
                                    [`skuValue${index + 1}`]: t,
                                    [item.label]: t,
                                    stock: 0,
                                    piece: 0,
                                    linePiece: 0,
                                    imgUrl: ""
                                };
                            }
                        })
                    )
                });
                temp = array;
            }
        });
        setSubmitList(temp);
    }
    useEffect(() => {
        console.log(submitList, 'SubmitList')
    }, [specContent])
    useEffect(() => {
        inputRef.current?.focus();
    }, [visible])
    useEffect(() => {
        (tagInputRef.current)?.childNodes[1].focus();
        (tagInputRef.current)?.childNodes[0].focus();
    }, [inputVisible, tagIndex])


    //删除一条sku
    const deleteSku = (index) => {
        const temp = [...submitList];
        temp.splice(index, 1);
        setSubmitList(temp);
        messageSuccess('删除sku成功');
    }

    const columns = [
        ...specContent.map(t => {
            return {
                title: t.label,
                width: 100,
                render: (item) => {
                    return item[t.label]
                }
            }
        }),
        {
            title: '图片地址',
            width: 200,
            render: (item, _, index) => {
                return (
                    <Space.Compact style={{ width: '100%' }}>
                        <Input
                            allowClear
                            onChange={(e) => {
                                submitList[index].imgUrl = e || 0
                                setSubmitList(submitList);
                            }}
                            defaultValue={submitList[index].imgUrl} />
                        <Button icon={<FolderOpenOutlined />}></Button>
                    </Space.Compact>
                )
            }
        },
        {
            title: '价格',
            width: 100,
            render: (item, _, index) => {
                return <InputNumber
                    min={0}
                    defaultValue={submitList[index].piece}
                    onChange={(e) => {
                        submitList[index].piece = e || 0
                        setSubmitList(submitList);
                    }}
                />
            }
        },
        {
            title: '划线价格',
            width: 100,
            render: (item, _, index) => {
                return <InputNumber
                    min={0}
                    defaultValue={submitList[index].linePiece}
                    onChange={(e) => {
                        submitList[index].linePiece = e || 0
                        setSubmitList(submitList);
                    }}
                />
            }
        },
        {
            title: '库存',
            width: 100,
            render: (item, _, index) => {
                return <InputNumber
                    min={0}
                    defaultValue={submitList[index].stock}
                    onChange={(e) => {
                        submitList[index].stock = e || 0
                        setSubmitList(submitList);
                    }}
                />
            }
        },
        {
            title: "action",
            key: "action",
            width: 100,
            dataIndex: "action",
            render: (text, record, index) => <Button onClick={() => deleteSku(index)} type="text" danger>删除</Button>
        }
    ]

    const ElInputContent = () => (
        <Input
            ref={inputRef}
            value={specLabelStr}
            style={{ width: 350 }}
            placeholder="请输入规格名称 按下Enter键确认"
            onPressEnter={onAddSpecLabel}
            onChange={(value) => setSpecLabelStr(value.target.value)}
            addonAfter={<span style={{ cursor: 'pointer' }} onClick={onAddSpecLabel}>确认添加</span>}
        />
    );




    const initData = (sku = [], specContent = []) => {
        setSubmitList(sku)
        setSpecContent(specContent)

    }
    const getData = () => {
        console.log("规格内容：", specContent, submitList)
        return { submitList, specContent };
    };
    useImperativeHandle(onRef, () => ({
        getData,
        initData
    }))

    useEffect(() => {
        return () => {
            setSpecContent([]);
            setSubmitList([]);
        }
    }, [])
    const ref = useRef(null);
    const containerWidth = useMemo(() => {
        if (ref.current) {
            console.log("宽度：", ref.current.clientWidth)
            return ref.current?.clientWidth;
        }


    })
    return <div style={{ width: '100%', }} >
        <Card
            ref={ref}
            style={{
                border: "none",
                height: "100%",
                width: "100%"
            }}
            title={
                <Popover placement="bottomLeft" trigger="click" content={ElInputContent}>
                    <Button type="dashed" icon={<PlusOutlined />} onClick={() => setVisible(!visible)} >添加规格</Button>
                </Popover>
            }
            extra={
                <h3>商品规格</h3>
            }
        >
            <div>
                {specContent.map((item, index) => {
                    return <div key={index}>
                        <h3>
                            <span style={{ marginRight: 12 }}>{item.label}</span>
                            <DeleteOutlined onClick={() => onDeleteSpec(index)} style={{ color: 'red' }} />
                        </h3>
                        <div style={{ display: 'flex', alignItems: 'center' }} ref={tagInputRef}>
                            <div> {item.tags.map((str, strKey) => (
                                <Tag
                                    style={{ fontSize: 16 }}
                                    color="processing" key={strKey}>
                                    <span>{str}</span>
                                    <CloseOutlined onClick={() => onDeleteSpecTag(index, strKey)} />
                                </Tag>
                            ))}</div>
                            {
                                inputVisible && index === tagIndex ?
                                    <Input
                                        placeholder="请输入规格值"
                                        value={inputTagValue}
                                        size="small"
                                        style={{ width: 120 }}
                                        onChange={(e) => setInputTagValue(e.target.value)}
                                        onBlur={() => onAddSpecTag(index)}
                                        onPressEnter={() => onAddSpecTag(index)}
                                    /> :
                                    <Tag
                                        icon={<PlusOutlined />}
                                        style={{ cursor: 'pointer' }}
                                        onClick={() => {
                                            setTagIndex(index);
                                            setInputVisible(!inputVisible)
                                        }}
                                    >添加规格值</Tag>
                            }
                        </div>
                    </div>
                })}
            </div>
            <Table

                rowKey="sku"
                rowSelection={{
                    key: 'sku',
                }}
                style={{
                    width: containerWidth,
                    maxWidth: "100%"
                }}
                scroll={{
                    y: 1000
                }}
                size="small"
                dataSource={submitList}
                columns={columns}
                pagination={false}

            />
        </Card>
    </div>


}
export default EditSkuTable;